import { CustomForm, OptionsProps } from '@/components/ProForm/interface/index';
import { requestTypeOptions, selectChildrenType, selectOptions, typeOptions } from '../../../form/component/right/basic/options';
import { v4 as uuidv4 } from 'uuid';
import { CustomTable } from '@/components/ProTable/interface';
import { defaultStyle } from '@/basic/style';
import { opAllItems, propertyGather } from '../../../form/component/right/basic/property';
import { cloneDeep } from 'lodash';
export function useAddColumnsForm(columnsDataGrid: CustomTable, dataGrid: CustomTable) {
  let opSelectItems = cloneDeep(propertyGather);
  let optionsAllItems = [];

  let addColumnsForm = reactive<CustomForm>({
    form: {},
    title: '',
    visible: false,
    formAttrs: {
      labelWidth: '140px'
    },
    transitionArr: [],
    options: [
      {
        type: 'input',
        hide: true,
        prop: 'id',
        label: 'id'
      },
      {
        type: 'input',
        hide: false,
        prop: 'prop',
        label: '绑定属性',
        rules: [
          {
            required: true,
            message: '绑定属性',
            trigger: 'blur'
          }
        ]
      },
      {
        type: 'input',
        hide: false,
        prop: 'label',
        label: '显示标签'
      },

      {
        type: 'input',
        hide: false,
        prop: 'width',
        label: '宽度'
      },
      {
        type: 'select',
        hide: false,
        prop: 'align',
        label: '文字对齐',
        defaultValue: 'center',
        children: [
          {
            label: '左',
            value: 'left',
            type: 'option'
          },
          {
            label: '中',
            value: 'center',
            type: 'option'
          },
          {
            label: '右',
            value: 'right',
            type: 'option'
          }
        ]
      },
      {
        type: 'select',
        hide: false,
        prop: 'fixed',
        label: '固定位置',
        attrs: {
          clearable: true
        },
        children: [
          {
            label: '左侧',
            value: 'left',
            type: 'option'
          },
          {
            label: '右侧',
            value: 'right',
            type: 'option'
          }
        ]
      },
      {
        type: 'select',
        hide: false,
        prop: 'type',
        label: '类型',
        defaultValue: '',
        children: [
          {
            label: '默认',
            value: '',
            type: 'option'
          },
          {
            label: '下标',
            value: 'index',
            type: 'option'
          },
          {
            label: '多选',
            value: 'selection',
            type: 'option'
          },
          {
            label: '单选',
            value: 'radio',
            type: 'option'
          },
          {
            label: '多级菜单',
            value: 'expand',
            type: 'option'
          },
          {
            label: '排序',
            value: 'sort',
            type: 'option'
          }
        ]
      },
      {
        type: 'select',
        hide: false,
        prop: 'tag',
        label: '标签展示',
        defaultValue: false,
        children: selectOptions
      },
      {
        type: 'select',
        hide: false,
        prop: 'isShow',
        label: '在表格展示',
        defaultValue: true,
        children: selectOptions
      },
      {
        type: 'select',
        hide: false,
        prop: 'isFilterEnum',
        label: '枚举过滤',
        defaultValue: true,
        children: selectOptions
      },
      {
        type: 'input',
        hide: false,
        prop: 'permissionCode',
        label: '字段权限码'
      },
      {
        type: 'select',
        hide: false,
        prop: 'enumProps.type',
        label: '枚举-接口类型',
        attrs: {
          clearable: true
        },
        children: selectChildrenType,
        changeMethod: () => changeEnumType()
      },
      {
        type: 'input',
        hide: true,
        prop: 'enumProps.options',
        label: '枚举-静态数据',
        attrs: {
          type: 'textarea'
        }
      },
      {
        type: 'input',
        hide: true,
        prop: 'enumProps.dictCode',
        label: '枚举-字典code'
      },
      {
        type: 'input',
        hide: true,
        prop: 'enumProps.label',
        label: '枚举-标签字段'
      },
      {
        type: 'input',
        hide: true,
        prop: 'enumProps.value',
        label: '枚举-值字段'
      },
      {
        type: 'select',
        hide: true,
        prop: 'enumProps.apiParams.type',
        label: '枚举-api-类型',
        children: requestTypeOptions
      },
      {
        type: 'input',
        hide: true,
        prop: 'enumProps.apiParams.url',
        label: '枚举-api-地址'
      },
      {
        type: 'input',
        hide: true,
        prop: 'enumProps.apiParams.validationField',
        label: '枚举-api-验证的字段'
      },
      {
        type: 'select',
        hide: false,
        prop: 'search.el',
        label: '查询-类型',
        attrs: {
          clearable: true
        },
        children: typeOptions,
        changeMethod: () => changeSearchType()
      },
      {
        type: 'input',
        hide: false,
        prop: 'search.label',
        label: '查询-标签'
      },
      {
        type: 'select',
        hide: false,
        prop: 'search.hide',
        label: '查询-是否隐藏',
        defaultValue: false,
        children: selectOptions
      },
      {
        type: 'input',
        hide: false,
        prop: 'search.key',
        label: '查询-绑定字段'
      },
      {
        type: 'input',
        hide: false,
        prop: 'search.tooltip',
        label: '查询-搜索提示'
      },
      {
        type: 'input',
        hide: false,
        prop: 'search.order',
        label: '查询-搜索项排序',
        attrs: {
          placeholder: '整数'
        }
      },
      {
        type: 'input',
        hide: false,
        prop: 'search.defaultValue',
        label: '查询-默认值'
      },
      {
        type: 'select',
        hide: false,
        prop: 'search.defaultValueType',
        label: '查询-默认类型',
        attrs: {
          clearable: true
        },
        children: [
          {
            label: '数字类型',
            value: 'number',
            type: 'option'
          }
        ]
      },
      {
        type: 'input',
        hide: false,
        prop: 'order',
        label: '排序'
      },
      {
        type: 'input',
        hide: false,
        prop: 'search.inputMethod',
        label: '查询-input方法',
        attrs: {
          type: 'textarea',
          style: defaultStyle,
          autosize: {
            minRows: 8,
            maxRows: 20
          }
        }
      },
      {
        type: 'input',
        hide: false,
        prop: 'search.changeMethod',
        label: '查询-change方法',
        attrs: {
          type: 'textarea',
          style: defaultStyle,
          autosize: {
            minRows: 8,
            maxRows: 20
          }
        }
      }
    ]
  });

  /**修改查询类型*/
  const changeSearchType = () => {
    const type = addColumnsForm.form['search.el'];

    // 根据类型显示对应查询可设置条件
    let searchFields = [];
    for (let f of addColumnsForm.options) {
      if (f.prop.includes('search.') && f.prop !== 'search.el') {
        searchFields.push(f.prop);
      }
    }
    formChangeItemStatus(addColumnsForm, searchFields, !type, 'hide');
    displayAttrsType(type);
  };
  /**
   * 设置显示属性
   */
  const displayAttrsType = displayField => {
    if (!displayField) return;

    let hideField = [];
    Object.keys(propertyGather).forEach(key => {
      if (key !== displayField) {
        hideField.push(...opSelectItems[key]);
      }
    });
    console.log(opSelectItems, 'opSelectItems');

    formChangeItemStatus(addColumnsForm, getProps(hideField), true, 'hide');
    formChangeItemStatus(addColumnsForm, getProps(opSelectItems[displayField]), false, 'hide');
  };

  const getProps = (arr: OptionsProps[]) => {
    return arr.map(item => item.prop as string);
  };

  /***
   * 初始化表单
   */
  const initForm = () => {
    optionsAllItems = getTypeField(opAllItems);
    Object.keys(propertyGather).forEach(key => {
      opSelectItems[key] = getTypeField(opSelectItems[key]);
    });
    addColumnsForm.options.push(...optionsAllItems);
  };

  /**
   * 获取对应类型的属性
   */
  const getTypeField = arr => {
    let returnArr = [];
    for (let item of arr) {
      if (item.prop.includes('attrs.')) {
        const newItem = {
          ...item,
          prop: item.prop.replace('attrs.', 'search.props.'),
          hide: true
        };
        returnArr.push(newItem);
      }
    }
    return returnArr;
  };

  onBeforeMount(() => {
    initForm();
  });

  /**
   * 修改枚举类型
   */
  const changeEnumType = (flag?) => {
    const type = addColumnsForm.form['enumProps.type'];

    const api = [
      'enumProps.apiParams.validationField',
      'enumProps.apiParams.type',
      'enumProps.apiParams.url',
      'enumProps.value',
      'enumProps.label'
    ];
    const dict = ['enumProps.dictCode', 'enumProps.value', 'enumProps.label'];
    const staticData = ['enumProps.options'];
    if (!flag) {
      Object.assign(addColumnsForm.form, {
        'enumProps.apiParams.validationField': '',
        'enumProps.apiParams.type': '',
        'enumProps.apiParams.url': '',
        'enumProps.value': '',
        'enumProps.label': '',
        'enumProps.dictCode': '',
        'enumProps.options': ''
      });
    }

    if (type) {
      if (type === 'api') {
        formChangeItemStatus(addColumnsForm, [...dict, ...staticData], true, 'hide');
        formChangeItemStatus(addColumnsForm, api, false, 'hide');
      } else if (type === 'dict') {
        formChangeItemStatus(addColumnsForm, [...api, ...staticData], true, 'hide');
        formChangeItemStatus(addColumnsForm, dict, false, 'hide');
        if (!flag) {
          Object.assign(addColumnsForm.form, {
            'enumProps.value': 'dicValue',
            'enumProps.label': 'dicCode'
          });
        }
      } else if (type === 'options') {
        formChangeItemStatus(addColumnsForm, [...api, ...dict], true, 'hide');
        formChangeItemStatus(addColumnsForm, staticData, false, 'hide');
      }
    } else {
      formChangeItemStatus(addColumnsForm, [...api, ...dict, ...staticData], true, 'hide');
    }
  };

  /**保存当前列 */
  const saveAddColumnsForm = async form => {
    if (form.id) {
      columnsDataGrid.data.forEach(item => {
        if (item.id === form.id) {
          Object.assign(item, form);
        }
      });
    } else {
      columnsDataGrid.data.unshift({
        ...form,
        id: uuidv4(),
        order: form.order || (dataGrid.columns.length || 1) * 10
      });
    }

    for (let item of columnsDataGrid.data) {
      item.order = parseInt(item.order);
    }

    arrSortItemsByName(columnsDataGrid.data, 'order', false);

    dataGrid.columns = [];
    for (let item of columnsDataGrid.data) {
      dataGrid.columns.push(item);
    }

    elMessage();
    setTimeout(() => {
      useGlobalStore().setGlobalState('formLoading', false);

      addColumnsForm.visible = false;
    }, 0);
  };
  /**打开类属性表单 */
  const openColumnsForm = (title: string, row?) => {
    formOpen(addColumnsForm, title, row);
    setTimeout(() => {
      changeEnumType(true);
      changeSearchType();
    }, 10);
  };

  return { addColumnsForm, saveAddColumnsForm, openColumnsForm };
}
